package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.saas.domain.entity.PayPlanUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PayPlanTeamEnum;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserTeamTransferSubForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 付款计划es和数据库格式转化
 * @author 魏荣杰
 * @date 2020/8/24 09:26
 * @since
 * @version
 */
@Component
public class PayPlanTeamTransferSubForm extends AbstractUserTeamTransferSubForm {

    private static final Logger LOG = LoggerFactory.getLogger(PayPlanTeamTransferSubForm.class);


    @Override
    public PaasFormDataEntity transferTeamToFormData(UserTeamEntity userTeamEntity) {
        PayPlanUserEntity payPlanUserEntity = (PayPlanUserEntity) userTeamEntity;
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(userTeamEntity);

        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(payPlanUserEntity));

        JSONObject data = new JSONObject();

        PayPlanTeamEnum[] payPlanTeamEnums = PayPlanTeamEnum.values();
        for (PayPlanTeamEnum payPlanTeamEnum : payPlanTeamEnums) {
            String dbAttr = payPlanTeamEnum.getDbAttr();
            String dataAttr = payPlanTeamEnum.getDataAttr();
            Integer fieldType = payPlanTeamEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }
        paasFormDataEntity.setData(data);

        return paasFormDataEntity;
    }

    @Override
    public UserTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {
        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        PayPlanTeamEnum[] payPlanTeamEnums = PayPlanTeamEnum.values();
        for (PayPlanTeamEnum payPlanTeamEnum : payPlanTeamEnums) {
            String dbAttr = payPlanTeamEnum.getDbAttr();
            String dataAttr = payPlanTeamEnum.getDataAttr();
            Integer fieldType = payPlanTeamEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);

        }
        PayPlanUserEntity payPlanUserEntity = JSON.parseObject(dbData.toJSONString(), PayPlanUserEntity.class);
        payPlanUserEntity.setAddTime(paasFormDataEntity.getAddTime());
        payPlanUserEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        payPlanUserEntity.setCorpid(paasFormDataEntity.getCorpid());
        payPlanUserEntity.setDel(paasFormDataEntity.getDel());
        payPlanUserEntity.setId(paasFormDataEntity.getId());

        return payPlanUserEntity;
    }
}
